package ca.etsmtl.log240.financej;
/*
 * Reports.java
 *
 * Created on March 17, 2008, 11:54 PM
 */

import java.sql.*;
import java.io.*;
import java.awt.Desktop;
import java.net.URI;

/**
 *
 * @author  rovitotv
 */
public class Reports extends javax.swing.JDialog {

    private Connection conn = null;

    /** Creates new form Reports */
    public Reports(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public void SetDBConnection(Connection dBConn) {
        conn = dBConn;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        startDateTextField = new javax.swing.JTextField();
        endDateTextField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        closeButton = new javax.swing.JButton();
        transactionsByAccountButton = new javax.swing.JButton();
        transactionsByCategoryButton = new javax.swing.JButton();

        setModal(true);

        jLabel1.setText("Start Date:");

        jLabel2.setText("End Date:");

        closeButton.setText("Close");
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        transactionsByAccountButton.setText("Transactions by Account");
        transactionsByAccountButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                transactionsByAccountButtonActionPerformed(evt);
            }
        });

        transactionsByCategoryButton.setText("Transactions by Category");
        transactionsByCategoryButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                transactionsByCategoryButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(closeButton)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(startDateTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 99, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2)
                        .addGap(3, 3, 3)
                        .addComponent(endDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(35, 35, 35))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(transactionsByCategoryButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(transactionsByAccountButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap(216, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(startDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(endDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(54, 54, 54)
                .addComponent(transactionsByAccountButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(transactionsByCategoryButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 118, Short.MAX_VALUE)
                .addComponent(closeButton)
                .addGap(20, 20, 20))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void transactionsByAccountButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TransactionsByAccountButtonActionPerformed
        
        try {
            TransactionAccountReport TransactionReportInstance = new TransactionAccountReport(conn, startDateTextField.getText(), endDateTextField.getText());
            TransactionReportInstance.Run();
			URI fichierURI = TransactionReportInstance.uRIDuFichier;
            if (Desktop.isDesktopSupported()) {
            	Desktop desktop = Desktop.getDesktop();
            	if (desktop.isSupported(Desktop.Action.BROWSE)) {
					desktop.browse(fichierURI);
            	}
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_TransactionsByAccountButtonActionPerformed

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CloseButtonActionPerformed
        setVisible(false);
    }//GEN-LAST:event_CloseButtonActionPerformed

    private void transactionsByCategoryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TransactionsByCategoryButtonActionPerformed
        try {
            TransactionCategoryReport TransactionReportInstance = new TransactionCategoryReport(conn, startDateTextField.getText(), endDateTextField.getText());
            TransactionReportInstance.run();
			URI fichierURI = TransactionReportInstance.uRIDuFichier;
            if (Desktop.isDesktopSupported()) {
            	Desktop desktop = Desktop.getDesktop();
            	if (desktop.isSupported(Desktop.Action.BROWSE)) {
					desktop.browse(fichierURI);
            	}
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }

    }//GEN-LAST:event_TransactionsByCategoryButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                Reports dialog = new Reports(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton closeButton;
    private javax.swing.JTextField endDateTextField;
    private javax.swing.JTextField startDateTextField;
    private javax.swing.JButton transactionsByAccountButton;
    private javax.swing.JButton transactionsByCategoryButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration//GEN-END:variables
}

class TransactionAccountReport {
    private Connection conn = null;
    private String startDate;
    private String endDate;
    private PrintWriter pw = null;
    private String accountName;
    public URI uRIDuFichier = null;
    
    public TransactionAccountReport(Connection dBConn, String startDateParam, String endDateParam) {
        conn = dBConn;
        startDate = startDateParam;
        endDate = endDateParam;
    }
    
    public void Run() {
        try {
            File ReportFile = new File("report.html");
            FileWriter fw = new FileWriter(ReportFile);
            uRIDuFichier = ReportFile.toURI();
            pw = new PrintWriter(fw);
            makeReportHeader();
            makeReportDetail();
            makeReportFooter();
            pw.close();
            fw.close();
         
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
    
    public void makeReportHeader() {
        pw.println("<html><title>FinanceJ Transaction Report by Account</title>");
        pw.println("<h1>Transaction Report by Account</h1>");
        pw.println("<h2>Start Date:" + startDate + " End Date:" + endDate + "</h2>");
    }
    
    public void makeReportDetail() {
        ResultSet AccountResult;
        Statement s;
        if (conn != null) {
            try {
                s = conn.createStatement();
                AccountResult = s.executeQuery("select * from account order by name");
                while (AccountResult.next()) {
                    accountName = AccountResult.getString(1);
                    pw.println("<h3>Account Name: " + accountName + "</h3>");
                    makeAccountDetail();
                }
            } catch (Throwable e) {
                System.out.println(" . . . exception thrown: in AccountListTableModel getValueAt");
                e.printStackTrace();
            }
        }
    }
    
    public void makeAccountDetail() {
        ResultSet LedgerResult;
        Statement s;
        float total = 0;

        pw.println("<table border=1>");
        pw.println("<tr>");
        pw.println("<th>Rec</th>");
        pw.println("<th>Transaction Date</th>");
        pw.println("<th>Payee</th>");
        pw.println("<th>Category</th>");
        pw.println("<th>Amount</th>");
        pw.println("</tr>");
        if (conn != null) {
            try {
                s = conn.createStatement();
                LedgerResult = s.executeQuery("select rec, tdate, payee, category, amount from ledger where account = '" + accountName + "' and tdate >= '" + startDate + "' and tdate <= '" + endDate + "' order by id");
                while (LedgerResult.next()) {
                  pw.println("<tr>");
                  pw.println("<td>" + LedgerResult.getInt(1) + "</td>");
                  pw.println("<td>" + LedgerResult.getDate(2) + "</td>");
                  pw.println("<td>" + LedgerResult.getString(3) + "</td>");
                  pw.println("<td>" + LedgerResult.getString(4) + "</td>");
				  pw.printf("<td>$%12.2f</td>", LedgerResult.getFloat(5));
                  pw.println("</tr>");
                  total += LedgerResult.getFloat(5);
                }
                
                pw.println("<tr>");
                pw.printf("<td colspan=\"4\">Total</td>");
                pw.printf("<td>$%12.2f</td>", total);
                pw.println("</tr>");
                pw.println("</table>");
            } catch (Throwable e) {
                System.out.println(" . . . exception thrown: in AccountListTableModel getValueAt");
                e.printStackTrace();
            }
        }
    }
    
    public void makeReportFooter() {
        pw.println("</html>");
    }
    
}

class TransactionCategoryReport {
    private Connection conn = null;
    private String startDate;
    private String endDate;
    private PrintWriter pw = null;
    private String categoryName;
    private float categoryBudget = 0;
    public URI uRIDuFichier = null;
    
    public TransactionCategoryReport(Connection dBConn, String startDateParam, String endDateParam) {
        conn = dBConn;
        startDate = startDateParam;
        endDate = endDateParam;
    }
    public void run() {
        try {
            File ReportFile = new File("report.html");
            FileWriter fw = new FileWriter(ReportFile);
            uRIDuFichier = ReportFile.toURI();
            pw = new PrintWriter(fw);
            makeReportHeader();
            makeReportDetail();
            makeReportFooter();
            pw.close();
            fw.close();
         
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
    
    public void makeReportHeader() {
        pw.println("<html><title>FinanceJ Transaction Report by Category</title>");
        pw.println("<h1>Transaction Report by Category</h1>");
        pw.println("<h2>Start Date:" + startDate + " End Date:" + endDate + "</h2>");
    }
    
    public void makeReportDetail() {
        ResultSet AccountResult;
        Statement s;
        if (conn != null) {
            try {
                s = conn.createStatement();
                AccountResult = s.executeQuery("select name, budget from category order by name");
                while (AccountResult.next()) {
                    categoryName = AccountResult.getString(1);
                    categoryBudget = AccountResult.getFloat(2);
                    pw.println("<h3>Category Name: " + categoryName + "</h3>");
                    makeAccountDetail();
                }
            } catch (Throwable e) {
                System.out.println(" . . . exception thrown: in AccountListTableModel getValueAt");
                e.printStackTrace();
            }
        }
    }
    
    public void makeAccountDetail() {
        ResultSet LedgerResult;
        Statement s;
        float total = 0;

        pw.println("<table border=1>");
        pw.println("<tr>");
        pw.println("<th>Rec</th>");
        pw.println("<th>Transaction Date</th>");
        pw.println("<th>Payee</th>");
        pw.println("<th>Account</th>");
        pw.println("<th>Amount</th>");
        pw.println("</tr>");
        if (conn != null) {
            try {
                s = conn.createStatement();
                LedgerResult = s.executeQuery("select rec, tdate, payee, account, amount from ledger where category = '" + categoryName + "' and tdate >= '" + startDate + "' and tdate <= '" + endDate + "' order by id");
                while (LedgerResult.next()) {
                  pw.println("<tr>");
                  pw.println("<td>" + LedgerResult.getInt(1) + "</td>");
                  pw.println("<td>" + LedgerResult.getDate(2) + "</td>");
                  pw.println("<td>" + LedgerResult.getString(3) + "</td>");
                  pw.println("<td>" + LedgerResult.getString(4) + "</td>");
                  pw.printf("<td>$%12.2f</td>", LedgerResult.getFloat(5));
                  pw.println("</tr>");
                  total += LedgerResult.getFloat(5);
                }
                
                pw.println("<tr>");
                pw.printf("<td colspan=\"2\">Budget</td>");
                pw.printf("<td>$%12.2f</td>", categoryBudget);
                pw.printf("<td>Total</td>");
                pw.printf("<td>$%12.2f</td>", total);
                pw.println("</tr>");
                pw.println("</table>");
            } catch (Throwable e) {
                System.out.println(" . . . exception thrown: in AccountListTableModel getValueAt");
                e.printStackTrace();
            }
        }
    }
    
    public void makeReportFooter() {
        pw.println("</html>");
    }
}

